'use strict';

const Controller = require('egg').Controller;

const OSS = require('ali-oss')
const path = require("path")

const client = new OSS({
    // yourregion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
    region: 'oss-cn-beijing',
    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
    accessKeyId: 'LTAI5tK6kteSpBd5VH68ngFL',
    accessKeySecret: 'RsoEDSobfQonH2h1ycqPJPVJw9jyGa',
    // 填写Bucket名称。
    bucket: 'caoxiang666',
});


class UploadController extends Controller {
    //查询图片列表
    async findList() {
        const { ctx } = this;
        try {
            const data = await client.list()
            ctx.body = {
                code: 200,
                data,
                mes: '查询成功'
            }
        } catch (err) {
            ctx.body = {
                code: 304,
                mes: '查询失败'
            }
        }
    }
    async upload() {
        const { ctx } = this;
        const file = ctx.request.files[0];
        try {
            let post = await client.put(file.filename, file.filepath)
            ctx.body = {
                code: 200,
                mes: '上传成功',
                data: post
            }
        } catch (err) {
            ctx.body = {
                code: 305,
                mes: '上传失败'
            }
        }
    }
    async download() {
        const { ctx } = this;
        let { name } = ctx.request.body
        try {
            let data = await client.get(name)
            console.log(data.res.requestUrls)
            ctx.body = {
                code: 200,
                mes: '下载成功',
                data: data.res.requestUrls[0]
            }
        } catch (err) {
            ctx.body = {
                code: 403,
                mes: '下载失败'
            }
        }
    }
    async delImage() {
        const { ctx } = this;
        let { name } = ctx.params
        try {
            let result = await client.delete(name);
            ctx.body={
                code:200,
                mes:'删除成功'
            }
        } catch (err) {
            // console.log(err);
            ctx.body={
                code:304,
                mes:"删除失败"
            }

        }
    }
}

module.exports = UploadController;
